package io.github.wanggit.antrpc.client.config.workers;

import io.github.wanggit.antrpc.IAntrpcContext;
import io.github.wanggit.antrpc.commons.config.CircuitBreakerConfig;
import io.github.wanggit.antrpc.commons.config.ConfigChangeTypeEnum;
import io.vavr.collection.List;

import java.util.HashMap;
import java.util.Map;

public class InterfaceBreakerConfigsChangeWorker extends AbstractChangeWorker {

    public InterfaceBreakerConfigsChangeWorker(IAntrpcContext antrpcContext, List<String> prefixs) {
        super(antrpcContext, prefixs);
    }

    @Override
    protected synchronized void internalFired(
            ConfigChangeTypeEnum changeType, String key, String oldValue, String newValue) {
        Map<String, CircuitBreakerConfig> interfaceBreakerConfigs =
                getAntrpcContext().getConfiguration().getInterfaceBreakerConfigs();
        if (null == interfaceBreakerConfigs) {
            interfaceBreakerConfigs = new HashMap<>();
            getAntrpcContext()
                    .getConfiguration()
                    .setInterfaceBreakerConfigs(interfaceBreakerConfigs);
        }
        String classNameAndField = replacePrefixs(key);
        int lastIdx = classNameAndField.lastIndexOf(".");
        String className = classNameAndField.substring(0, lastIdx);
        String fieldName = classNameAndField.substring(lastIdx + 1);
        CircuitBreakerConfig circuitBreakerConfig =
                interfaceBreakerConfigs.containsKey(className)
                        ? interfaceBreakerConfigs.get(className)
                        : new CircuitBreakerConfig();
        setFieldValue(circuitBreakerConfig, fieldName, newValue);
        interfaceBreakerConfigs.put(className, circuitBreakerConfig);
        getAntrpcContext()
                .getResilience4jCircuitBreakerContainer()
                .reInitInterfaceConfig(getAntrpcContext().getConfiguration());
    }
}
